<script setup>
import {ref,onMounted,watch} from 'vue'
import {queryClazzApi,addClazzApi,queryClazzByIdApi,updateClazzApi,deleteClazzApi} from '@/api/clazz'
import {queryAllEmpApi} from '@/api/emp'
import { ElMessage,ElMessageBox } from 'element-plus';

//定义基础数据
//学科数据
const courses = ref([{ name: 'java', value: 1 },{ name: '前端', value: 2 },{ name: '大数据', value: 3 },{ name: 'Python', value: 4 },{ name: 'Go', value: 5 },{ name: '嵌入式', value: 6 }])
//班主任名称数据
const masterNames = ref([]);
//从员工的方法中得到班主任
async function queryAllEmps(){
  const result=await queryAllEmpApi()
  if(result.code){
    masterNames.value=result.data
  }
}

//钩子函数
onMounted(()=>{
  serach()
  queryAllEmps()
})

//定义条件查找框的对象
const searchClazz=ref({
  name:'',
  data:[],
  begin:'',
  end:''
})

//查询
async function serach(){
  const result=await queryClazzApi(searchClazz.value.name,
                                  searchClazz.value.begin,
                                  searchClazz.value.end,
                                  currentPage.value,
                                  pageSize.value
  )
  if(result.code){
    total.value=result.data.total
    clazzList.value=result.data.rows
  }
}

//清空
function clear(){
  searchClazz.value={
  name:'',
  begin:'',
  end:''
}
serach()
}

//新增班级
function add(){
  dialogVisible.value=true
  dialogTitle.value='新增班级'
  clazz.value={
                name:'',
                room:'',
                beginDate:'',
                endDate:'',
                masterId:'',
                subject:''
}
if(clazzFormRef.value){
  clazzFormRef.value.resetFields();
  }
}

//定义表格中的数据数组
const clazzList=ref([])
//当前页数
const currentPage=ref(1)
//每页显示条目个数
const pageSize=ref(5)
//数据总数
const total=ref(0)
//当每页展示条数改变时
function handleSizeChange(){
  serach()
}
//当每页展示页码改变时
function handleCurrentChange(){
  serach()
}

//watch侦听
watch(()=>searchClazz.value.data,(newVal,oldVal)=>{
  if(searchClazz.value.data && searchClazz.value.data.length>0){
    searchClazz.value.begin=searchClazz.value.data[0]
    searchClazz.value.end=searchClazz.value.data[1]
  }else{
    searchClazz.value.begin=''
    searchClazz.value.end=''
  }
})

//弹出表单的名称
const dialogTitle=ref('')

//控制新增和编辑班级表单的开关
const dialogVisible=ref(false)
//班级数据
const clazz=ref({
                name:'',
                room:'',
                beginDate:'',
                endDate:'',
                masterId:'',
                subject:''
})
//保存新增和编辑的班级数据
async function save(){
   //表单校验
   if(! clazzFormRef) return
  await clazzFormRef.value.validate(async(valid,fields)=>{
    if(valid){
      //通过校验
      let result
      if(clazz.value.id){
        //有id做修改
        result=await updateClazzApi(clazz.value)
      }else{
        //没有id做新增
        
        result=await addClazzApi(clazz.value)
      }
      
  if(result.code){
    dialogVisible.value=false
    ElMessage.success('保存成功')
    serach()
  }else{
    ElMessage.error(result.msg)
  }
      }else{
    ElMessage.error('表单校验不通过，请重新输入')
  }
    })
  }
  


//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '班级名称为必填项',trigger: 'blur' },
    { min: 4, max: 30, message: '班级名称非法', trigger: 'blur' }
  ],
  room: [
    { min: 1, max: 20,message: '长度在1-10之间', trigger: 'blur' }
  ],
  beginDate: [
    { required: true,message: '请选择开课时间', trigger: 'change' }
  ],
  endDate: [
    { required: true,message: '请选择结课时间', trigger: 'change' },
    //^代表以这个数字开头，$代表结尾，[]代表限制数字的范围，以\d代表这个位置仅能是数字，\d{}代表有多少位是数字
  ],
  subject: [
    { required: true,message: '请选择学科',trigger: 'change' }
  ]
})

//提交时进行表单校验
//为表单绑定引用，定义响应式数据,为了引用表单
const clazzFormRef=ref()

//编辑:查询回显
async function edit(id){
  const result=await queryClazzByIdApi(id)
  if(result.code){
    dialogVisible.value=true
    dialogTitle.value='编辑班级'
    clazz.value=result.data
  }else{
    ElMessage.error(result.msg)
  }
}

//删除
function deleteById(id){
  ElMessageBox.confirm(
    '您确定要删除该班级吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
     const result=await deleteClazzApi(id)
     if(result.code){
      ElMessage.success('删除成功')
      serach()
     }else{
      ElMessage.error(result.msg)
     }
    })
    .catch(() => {
      ElMessage.info('取消操作')
    })
}
</script>

<template>
  <h1>班级管理</h1>
  <!-- 表头的表单项和按钮 -->
  <div class="search">
    <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
    <el-form-item label="班级姓名">
      <el-input v-model="searchClazz.name" placeholder="请输入班级名称" />
    </el-form-item>

    <!-- 注意：value-format绑定日期的输出格式，YYYY-MM-DD需要大写 -->
    <el-form-item label="结课时间">
      <el-date-picker
        v-model="searchClazz.data"
        type="daterange"
        range-separator="到"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="serach">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  </div>
  <!-- 新增班级按钮 -->
  <div class="add">
    <el-button type="primary" @click="add"> + 新增班级</el-button>
  </div>
  <!-- 表格区域 -->
  <el-table :data="clazzList" border style="width: 100%">
    <!-- type="index"让表格序号列顺序排列1234 -->
     <!-- 用align使数据居中 -->
    <el-table-column type="index" label="序号" width="80"  align="center"/>
    <el-table-column prop="name" label="班级名称" width="150"  align="center"/>
    <el-table-column prop="room" label="班级教室" width="100"  align="center"/>
    <el-table-column prop="masterName" label="班主任" width="100"  align="center"/>
    <el-table-column prop="beginDate" label="开课时间" width="150"  align="center"/>
    <el-table-column prop="endDate" label="结课时间" width="150"  align="center"/>
    <el-table-column prop="status" label="状态" width="100"  align="center"/>
    <el-table-column prop="updateTime" label="最后操作时间" width="200"  align="center"/>
    <el-table-column prop="address" label="操作"  align="center">
      <!-- 插槽引入按钮 -->
      <template #default="scope">
        <el-button type="primary" size="small" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页区域 pageSize:每页显示条目个数 currentPage:当前页数-->
  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 新增和修改部门的弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" size="small" >
      <el-form :model="clazz" ref="clazzFormRef" :rules="rules" label-width="80px" style="width: 50%;">
        <!-- 第一行 -->
            <el-form-item label="班级名称" prop="name">
              <el-input v-model="clazz.name" placeholder="请输入班级名称"></el-input>
            </el-form-item>
        <!-- 第二行 -->
            <el-form-item label="班级教室" prop="room">
              <el-input v-model="clazz.room" placeholder="请填写班级教室"></el-input>
            </el-form-item>

       <!-- 第三行 value-format指定绑定值的格式-->
       <el-form-item label="开课时间" prop="beginDate">
              <el-date-picker v-model="clazz.beginDate" type="date" style="width: 100%;" placeholder="请选择开课时间" value-format="YYYY-MM-DD" ></el-date-picker>
            </el-form-item>
            <!-- 第四行 -->
            <el-form-item label="结课时间" prop="endDate">
              <el-date-picker v-model="clazz.endDate" type="date" style="width: 100%;" placeholder="请选择结课时间" value-format="YYYY-MM-DD" ></el-date-picker>
            </el-form-item>
            <!-- 第五行 -->
            <el-form-item label="班主任">
              <el-select v-model="clazz.masterId" placeholder="请选择" style="width: 100%;">
              <el-option v-for="masterName in masterNames" :label="masterName.name" :value="masterName.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 第六行 -->
          <el-form-item label="学科" prop="subject">
              <el-select v-model="clazz.subject" placeholder="请选择" style="width: 100%;">
              <el-option v-for="course in courses" :label="course.name" :value="course.value"></el-option>
            </el-select>
          </el-form-item>
      </el-form>
      
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
  </el-dialog>
</template>

<style scoped>
.search{
  margin: 20px 0;
}
.add{
  margin-bottom: 20px;
}

</style>